home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7728 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: A curly one for gurus: possible to create a value array of derived objects?
  5. Date: Thu, 15 Feb 1996 14:21:16 +0100
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <3123334C.446B9B3D@intellektik.informatik.th-darmstadt.de>
  8. References: <4fuho2$d3s@mblisd.macqbl.com.au>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. Steven James Brown wrote:
  16. > Ok This is a real curly question:
  17. > Is it possible to create (and manage) a "value" array of objects from
  18. > derived classes?
  19. > E.g:
  20. > struct A { virtual char* name() { return "A"; } };
  21. > struct B : public A { int    data1; virtual char* name() { return "B"; }  };
  22. > struct C : public A { double data2; virtual char* name() { return "C"; }  };
  23. > To be able to provide access to an array of B's and C's without occuring
  24. > the overhead of pointer indirection, I am hoping it is somehow possible to
  25. > have something like:
  26. > #include <stdio.h>
  27. > main()
  28. > {
  29. >     A* a = new A[10];
  30. >     B b;
  31. >     C c;
  32. >     a[0] = b;
  33. >     a[1] = c;
  34. >     printf("%s\n", a[0].name());
  35. >     printf("%s\n", a[1].name());
  36. > }
  37. > The output from this (as you may have already guessed) is
  38. > A
  39. > A
  40. > and not
  41. > B
  42. > C
  43. > The problem here is I guess "data slicing" and the use of the default operator=.
  44. > Is it possible to somehow get over this
  45. > by faking a union? I can't use unions in practice because my derived classes
  46. > have (default) constructors.
  47. > The idea for this came from the "Composite" pattern in the Design Patterns
  48. > book by Gamma/Helm/Johnson/Vlissides. The "A" class above being the "Composite"
  49. > object, and the "B" and "C" being the "Component" objects.
  50.  
  51. IMO the easiest way is to wrap pointers to objects of type A,B,C, ...and maintain
  52. an array of wrapped objects instead.
  53.  
  54.     Enno
  55.